<template>
    <div class="contener">
        <div class="tree-page">
            <!-- 左侧树 -->
            <div class="tree-menu">
                <base-tree
                    :data="baseTreeConfig.data"
                    :loading="baseTreeConfig.loading"
                    :currentNodeKey="baseTreeConfig.currentNodeKey"
                    :filterShow="baseTreeConfig.filterShow"
                    @NodeClick="handelTreeClick"
                    @Check="handelCheck"
                />
            </div>
            <!-- 页面 -->
            <div class="page">
                <!-- 搜索 -->
                <transition
                    @before-enter="_beforeEnter"
                    @enter="_enter"
                    @after-enter="_afterEnter"
                    @before-leave="_beforeLeave"
                    @leave="_leave"
                    @after-leave="_afterLeave"
                >
                    <div
                        class="search-contener"
                        ref="searchContener"
                        v-show="searchFormConfig.searchContenerShow"
                    >
                        <base-form
                            :formItems="searchFormConfig.formItems"
                            :formData="searchFormConfig.formSubmit"
                            ref="searchForm"
                            @onButtonClick="searchBarButtonClick"
                        />
                    </div>
                </transition>
                <div class="datas-contener">
                    <!-- 操作项 -->
                    <div class="option-contener">
                        <data-options
                            @buttonClick="handelOptionClick"
                            :leftConfig="dataOptionConfig.leftConfig"
                            :rightConfig="dataOptionConfig.rightConfig"
                        />
                    </div>
                    <!-- 编辑展示项 -->
                    <div class="table-contener">
                        <monaco-editor
                            :editorOptions="editorOptions"
                            @onCodeChange="onCodeChange"
                        />
                    </div>
                </div>
            </div>
        </div>
        <!-- 弹框 -->
        <el-dialog
            :title="dialogConfig.title"
            :visible.sync="dialogConfig.show"
            :width="dialogConfig.width"
            v-dialogDrag
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            append-to-body
        >
            <!-- 新增 -->
            <div class="dialog-content" v-if="dialogConfig.key === 'addData'">
                <base-form
                    :formItems="addFormConfig.formItems"
                    :formData="addFormConfig.formSubmit"
                    :formConfig="addFormConfig.formConfig"
                    :formRules="addFormConfig.formRule"
                    ref="addForm"
                    @onButtonClick="addFormButtonClick"
                />
            </div>
            <!-- Rename -->
            <div class="dialog-content" v-if="dialogConfig.key === 'reNameKey'">
                <base-form
                    :formItems="reNameKeyFormConfig.formItems"
                    :formData="reNameKeyFormConfig.formSubmit"
                    :formConfig="reNameKeyFormConfig.formConfig"
                    :formRules="reNameKeyFormConfig.formRule"
                    ref="reNameForm"
                    @onButtonClick="reNameKeyFormButtonClick"
                />
            </div>
            <div class="dialog-content" v-if="dialogConfig.key === 'setTtlKey'">
                <base-form
                    :formItems="setTtlFormConfig.formItems"
                    :formData="setTtlFormConfig.formSubmit"
                    :formConfig="setTtlFormConfig.formConfig"
                    :formRules="setTtlFormConfig.formRule"
                    ref="setTtlForm"
                    @onButtonClick="setTtlFormButtonClick"
                />
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button size="small" @click="handelCloseDialog"
                    >取 消</el-button
                >
                <el-button
                    size="small"
                    type="primary"
                    @click="handelCofimeDialog"
                    >确 定</el-button
                >
            </span>
        </el-dialog>
    </div>
</template>
<script>
import BaseTree from '@/components/baseTree/index'
import BaseForm from '@/components/baseForm/index'
import DataOptions from '@/components/dataOptions/index'
import monacoEditor from '@/components/monacoEditor/index'
import globalMixin from '@/mixins/global'
import {
    redisManagerTree,
    redisManagerInfo,
    redisManagerSave,
    redisManagerReName,
    redisManagerDel,
    redisManagerSetTtl
} from '@/http/apis/tool/redis/index'
import { getDictDatas } from '@/plugins/dict'
export default {
    components: {
        BaseTree,
        BaseForm,
        DataOptions,
        monacoEditor
    },
    mixins: [globalMixin],
    data() {
        return {
            // 通用树组件配置
            baseTreeConfig: {
                // tree的数据
                data: [],
                // tree的加载状态
                loading: false,
                // tree选中的树
                currentNodeKey: '',
                // 过滤显示
                filterShow: true
            },
            //编辑器
            editorOptions: {
                value: '',
                newVal: '',
                theme: 'vs-dark'
            },
            // 搜索表单配置
            searchFormConfig: {
                formItems: [
                    [
                        {
                            ltype: 'input',
                            placeholder: 'Key',
                            label: 'Key',
                            prop: 'key',
                            width: 'w-auto',
                            readonly: true
                        },
                        {
                            ltype: 'input',
                            placeholder: 'TTL',
                            label: 'TTL(s)',
                            prop: 'ttl',
                            width: 'w-auto',
                            readonly: true
                        },
                        {
                            ltype: 'input',
                            placeholder: 'Type',
                            label: 'Type',
                            prop: 'type',
                            width: 'w-auto',
                            readonly: true
                        },
                        {
                            ltype: 'input',
                            placeholder: 'Size',
                            label: 'Size',
                            prop: 'size',
                            width: 'w-auto',
                            readonly: true
                        }
                    ]
                ],
                formSubmit: {
                    key: '',
                    ttl: '',
                    type: '',
                    size: ''
                },
                formConfig: {
                    labelPosition: 'right', // label对齐方式
                    labelWidth: 'auto'
                },
                // 搜索控件是否显示
                searchContenerShow: true
            },
            // 数据操作项配置
            dataOptionConfig: {
                // 左侧按钮配置
                leftConfig: [
                    {
                        ltype: 'input',
                        label: 'Add Key',
                        prop: 'addData',
                        type: 'primary',
                        width: 'w-1',
                        hasPermi: ['tool/redis/manager/save']
                    },
                    {
                        prop: 'reNameKey',
                        label: 'Rename',
                        type: 'primary',
                        disabled: false,
                        hasPermi: ['tool/redis/manager/reName']
                    },
                    {
                        prop: 'deleteTableData',
                        label: 'Delete Key',
                        icon: 'el-icon-delete',
                        type: 'danger',
                        disabled: false,
                        hasPermi: ['tool/redis/manager/del']
                    },
                    {
                        prop: 'setTtlKey',
                        label: 'Set TTL',
                        type: 'primary',
                        disabled: false,
                        hasPermi: ['tool/redis/manager/setTtl']
                    },
                    {
                        prop: 'updateData',
                        label: 'Save',
                        type: 'primary',
                        disabled: false,
                        hasPermi: ['tool/redis/manager/save']
                    }
                ],
                rightConfig: []
            },
            // 表格配置
            baseTableConfig: {
                // 表格数据
                tableData: [],
                // 表格头数据
                tableHeader: [
                    {
                        type: 'selection',
                        width: 50,
                        fixed: 'left',
                        label: '选择',
                        visible: true
                    },
                    {
                        type: 'index',
                        label: '序号',
                        width: 50,
                        visible: true
                    },
                    {
                        prop: 'userName',
                        label: '用户名称',
                        visible: true
                    },
                    {
                        prop: 'phone',
                        label: '手机号码',
                        visible: true
                    },
                    {
                        prop: 'deptName',
                        label: '部门',
                        visible: true
                    },
                    {
                        prop: 'status',
                        type: 'switch',
                        label: '状态',
                        visible: true
                    },
                    {
                        prop: 'createTime',
                        label: '创建时间',
                        visible: true
                    },
                    {
                        label: '操作',
                        type: 'handle',
                        fixed: 'right',
                        visible: true
                    }
                ],
                // 表格配置
                tableConfig: {
                    loading: false
                },
                // 选中的表格数据
                tableCheckedDatas: []
            },
            // 弹框配置
            dialogConfig: {
                // 弹框标题
                title: '新增',
                // 是否显示
                show: false,
                // 宽度
                width: 'auto',
                // 弹框标识(用来区分弹框内容)
                key: ''
            },
            // 查询表格数据的参数
            queryTableParams: {},

            // 新增表单配置
            addFormConfig: {
                // 表单项
                formItems: [
                    [
                        {
                            ltype: 'input',
                            placeholder: '请输入key',
                            label: 'key',
                            prop: 'key',
                            width: 'w-1'
                        }
                    ],
                    [
                        {
                            ltype: 'input',
                            type: 'textarea',
                            rows: '20',
                            placeholder: '请输入value',
                            label: 'value',
                            prop: 'value',
                            width: 'w-1'
                        }
                    ],
                    [
                        {
                            ltype: 'select',
                            placeholder: '请选择时间类别',
                            label: 'type',
                            prop: 'timeType',
                            width: 'w-1',
                            options: getDictDatas('tool_redis_time_type')
                        }
                    ],
                    [
                        {
                            ltype: 'input',
                            placeholder: '请输入expire，默认秒',
                            label: 'expire',
                            prop: 'expire',
                            width: 'w-1'
                        }
                    ]
                ],
                // 提交项
                formSubmit: {
                    key: '',
                    value: '',
                    expire: '',
                    timeType: ''
                },
                // 配置项
                formConfig: {
                    labelPosition: 'right', // label对齐方式
                    labelWidth: '80px'
                },
                // 验证项
                formRule: {
                    key: [
                        {
                            required: true,
                            message: '请输入key',
                            trigger: 'blur'
                        }
                    ],
                    value: [
                        {
                            required: true,
                            message: '请输入value',
                            trigger: 'blur'
                        }
                    ]
                }
            },
            // ReName表单配置
            reNameKeyFormConfig: {
                // 表单项
                formItems: [
                    [
                        {
                            ltype: 'input',
                            placeholder: '请输入key',
                            label: 'key',
                            prop: 'newKey',
                            width: 'w-1'
                        }
                    ]
                ],
                // 提交项
                formSubmit: {
                    newKey: '1111',
                    oldKey: ''
                },
                // 配置项
                formConfig: {
                    labelPosition: 'right', // label对齐方式
                    labelWidth: '80px'
                },
                // 验证项
                formRule: {
                    key: [
                        {
                            required: true,
                            message: '请输入key',
                            trigger: 'blur'
                        }
                    ]
                }
            },
            // setTtl表单配置
            setTtlFormConfig: {
                // 表单项
                formItems: [
                    [
                        {
                            ltype: 'select',
                            placeholder: '请选择时间类别',
                            label: '时间类别',
                            prop: 'timeType',
                            width: 'w-1',
                            options: getDictDatas('tool_redis_time_type')
                        }
                    ],
                    [
                        {
                            ltype: 'input',
                            placeholder: '请输入TTL',
                            label: 'TTL',
                            prop: 'ttl',
                            width: 'w-1'
                        }
                    ]
                ],
                // 提交项
                formSubmit: {
                    key: '1111',
                    ttl: '',
                    timeType: '1'
                },
                // 配置项
                formConfig: {
                    labelPosition: 'right', // label对齐方式
                    labelWidth: '80px'
                },
                // 验证项
                formRule: {
                    ttl: [
                        {
                            required: true,
                            message: '请输入TTL',
                            trigger: 'blur'
                        }
                    ],
                    timeType: [
                        {
                            required: true,
                            message: '请选择时间类别',
                            trigger: 'blur'
                        }
                    ]
                }
            }
        }
    },
    created() {
        this.initPage()
    },
    methods: {
        /**
         * 页面开始
         */
        async initPage() {
            // 查询缓存树列表
            await this.redisManagerTree()
            // 查询用户列表
            this.redisManagerInfo(this.queryTableParams)
        },
        /**
         * 左侧缓存树相关
         */
        /**
         * 查询缓存树列表
         */
        async redisManagerTree() {
            this.baseTreeConfig.loading = true
            try {
                let res = await redisManagerTree()
                if (res && res.data) {
                    this.baseTreeConfig.data = res.data
                } else {
                    this.baseTreeConfig.data = []
                }
                this.baseTreeConfig.loading = false
            } catch (error) {
                this.baseTreeConfig.loading = false
            }
        },
        /**
         * 树点击
         * @param {Object} params
         */
        handelTreeClick(params) {
            this.baseTreeConfig.currentNodeKey = params.item.name
            // 组装查询条件
            this.queryTableParams = {
                key: params.item.name
            }
            // 查询数据
            this.redisManagerInfo(this.queryTableParams)
        },

        /**
         * 中间表格相关
         */

        /**
         * 查询表格数据
         */
        async redisManagerInfo(params) {
            this.baseTableConfig.tableConfig.loading = true
            try {
                let res = await redisManagerInfo(params)
                if (res.data) {
                    this.editorOptions.value = res.data.val
                    this.searchFormConfig.formSubmit.key = res.data.key
                    this.searchFormConfig.formSubmit.ttl = res.data.ttl
                    this.searchFormConfig.formSubmit.type = res.data.type
                    this.searchFormConfig.formSubmit.size = res.data.size
                }
                this.baseTableConfig.tableConfig.loading = false
            } catch (error) {
                this.baseTableConfig.tableConfig.loading = false
            }
        },

        /**
         * 搜索栏相关
         */
        /**
         * 搜索栏按钮点击
         * @param {Object} params
         */
        searchBarButtonClick(params) {
            try {
                this[params.prop]()
            } catch (error) {
                throw new Error(error)
            }
        },

        /**
         * 操作栏相关
         */
        /**
         * 操作项点击
         * @param {*} params
         */
        handelOptionClick(params) {
            this[params] ? this[params]() : null
        },
        /**
         * 切换搜索栏的显示状态
         */
        switchSearchStatus() {
            this.searchFormConfig.searchContenerShow = !this.searchFormConfig
                .searchContenerShow
        },
        /**
         * 刷新表格数据
         */
        refreshTableData() {
            // 将当前表格数据设置为空
            this.baseTableConfig.tableData = []
            this.queryTableData(this.queryTableParams)
        },

        /**
         * 设置表格显示隐藏列(弹框确认)
         */
        switchTableColumnButtonClick() {
            let newData = this.$refs.baseTransfer.backCheckedData()
            if (newData && newData.length > 0) {
                this.baseTableConfig.tableHeader.forEach(ele => {
                    ele.visible = !newData.includes(ele.label)
                })
            } else {
                this.baseTableConfig.tableHeader.forEach(ele => {
                    ele.visible = true
                })
            }
            this.handelCloseDialog()
        },

        /**
         * 新增数据(打开弹框)
         */
        addData() {
            // 打开新增弹框
            let dialogParams = {
                title: 'Add New Key',
                width: '60%',
                show: true,
                key: 'addData'
            }
            this.handelOpenDialog(dialogParams)
        },
        /**
         * 新增数据确认提交(弹框确认)
         */
        addFormButtonClick() {
            this.$refs['addForm'].submitForm(async res => {
                if (res) {
                    res.expire = Number(res.expire)
                    if (res.expire != 0 && res.timeType == '') {
                        this.$message({
                            type: 'error',
                            message: '请检查时间类别是否为空!'
                        })
                    } else {
                        let assRes = await redisManagerSave(res)
                        if (assRes && assRes.code === 0) {
                            this.$message.closeAll()
                            this.$message.success({ message: '新增成功！' })
                        } else {
                            this.$message.closeAll()
                            this.$message.error({ message: '新增失败！' })
                        }
                        this.handelCloseDialog()
                        // 查询数据
                        this.initPage()
                        this.initAddForm()
                    }
                } else {
                    this.initAddForm()
                }
            })
        },
        /**
         * 重命名(打开弹框)
         */
        reNameKey() {
            if (undefined == this.searchFormConfig.formSubmit.key) {
                this.$message({
                    type: 'error',
                    message: '请先点击左侧选择Key值!'
                })
            } else {
                this.reNameKeyFormConfig.formSubmit.oldKey = this.searchFormConfig.formSubmit.key
                this.reNameKeyFormConfig.formSubmit.newKey = this.searchFormConfig.formSubmit.key

                // 打开新增弹框
                let dialogParams = {
                    title: 'Rename Key',
                    width: '30%',
                    show: true,
                    key: 'reNameKey'
                }
                this.handelOpenDialog(dialogParams)
            }
        },
        /**
         * 重命名确认提交(弹框确认)
         */
        reNameKeyFormButtonClick() {
            this.$refs['reNameForm'].submitForm(async res => {
                if (res) {
                    if (res.oldKey === res.newKey) {
                        this.$message({
                            type: 'error',
                            message: '修改后的值与原来的值一致，请检查!'
                        })
                    } else {
                        let assRes = await redisManagerReName(res)
                        if (assRes && assRes.code === 0) {
                            this.$message.closeAll()
                            this.$message.success({ message: '修改成功！' })
                        } else {
                            this.$message.closeAll()
                            this.$message.error({ message: '修改失败！' })
                        }
                        this.handelCloseDialog()
                        // 查询数据
                        this.initPage()
                    }
                } else {
                    this.initAddForm()
                }
            })
        },

        /**
         * 设置过期时间(打开弹框)
         */
        setTtlKey() {
            if (undefined == this.searchFormConfig.formSubmit.key) {
                this.$message({
                    type: 'error',
                    message: '请先点击左侧选择Key值!'
                })
            } else {
                this.setTtlFormConfig.formSubmit.ttl = this.searchFormConfig.formSubmit.ttl
                this.setTtlFormConfig.formSubmit.key = this.searchFormConfig.formSubmit.key

                // 打开新增弹框
                let dialogParams = {
                    title: 'Set Key TTL',
                    width: '30%',
                    show: true,
                    key: 'setTtlKey'
                }
                this.handelOpenDialog(dialogParams)
            }
        },
        /**
         * 设置过期时间(弹框确认)
         */
        setTtlFormButtonClick() {
            this.$refs['setTtlForm'].submitForm(async res => {
                if (res) {
                    let assRes = await redisManagerSetTtl(res)
                    if (assRes && assRes.code === 0) {
                        this.$message.closeAll()
                        this.$message.success({ message: '修改成功！' })
                    } else {
                        this.$message.closeAll()
                        this.$message.error({ message: '修改失败！' })
                    }
                    this.handelCloseDialog()
                    // 查询数据
                    this.initPage()
                } else {
                    this.initAddForm()
                }
            })
        },
        /**
         * 初始化新增表单
         */
        initAddForm() {
            this.addFormConfig.formSubmit = {}
            this.$refs.addForm.resetForm()
        },

        /**
         * 删除数据
         */
        deleteTableData() {
            if (undefined == this.searchFormConfig.formSubmit.key) {
                this.$message({
                    type: 'error',
                    message: '请先点击左侧选择Key值!'
                })
                return
            }
            let params = {
                key: this.searchFormConfig.formSubmit.key
            }

            this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(async () => {
                    let res = await redisManagerDel(params)
                    if (res && res.code == 0) {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        })
                        //删除后将编辑框值为空
                        this.editorOptions.value = ''
                    } else {
                        this.$message({
                            type: 'error',
                            message: '删除失败!'
                        })
                    }
                    // 查询数据
                    this.initPage()
                })
                .catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    })
                })
        },

        /**
         * 弹框相关
         */
        /**
         * 打开弹框
         * @param {*} params
         */
        handelOpenDialog(params) {
            this.dialogConfig = params
        },
        /**
         * 初始化弹框
         */
        handelInitDialog() {
            this.dialogConfig = {
                title: '',
                show: false,
                width: '',
                key: ''
            }
        },
        /**
         * 关闭弹框
         */
        handelCloseDialog() {
            this.handelInitDialog()
        },
        /**
         * 弹框确定
         */
        handelCofimeDialog() {
            // 表格列筛选的弹框
            if (this.dialogConfig.key === 'tableColumn') {
                this.switchTableColumnButtonClick()
            } else if (this.dialogConfig.key === 'addData') {
                this.addFormButtonClick()
            } else if (this.dialogConfig.key === 'updateTableData') {
                this.updateFormButtonClick()
            } else if (this.dialogConfig.key === 'reNameKey') {
                this.reNameKeyFormButtonClick()
            } else if (this.dialogConfig.key === 'setTtlKey') {
                this.setTtlFormButtonClick()
            }
        },
        onCodeChange(param) {
            this.editorOptions.newVal = param
        },
        handelCheck(value) {
            this.editorOptions.value = value
        },
        //保存更新后的数据
        async updateData() {
            if (undefined == this.searchFormConfig.formSubmit.key) {
                this.$message({
                    type: 'error',
                    message: '请先点击左侧选择Key值!'
                })
            } else {
                let params = {
                    key: this.searchFormConfig.formSubmit.key,
                    value: this.editorOptions.newVal,
                    expire: this.searchFormConfig.formSubmit.ttl
                }
                let assRes = await redisManagerSave(params)
                if (assRes && assRes.code === 0) {
                    this.$message.success({ message: '修改成功！' })
                } else {
                    this.$message.error({ message: '修改失败！' })
                }
            }
        }
    }
}
</script>
<style lang="scss" scoped>
.more-dropdown {
    margin-left: 10px;
}
.dialog-content {
    @include box_flex(
        $width: 100%,
        $height: auto,
        $direction: column,
        $justify: flex-start,
        $align: center
    );
}
</style>
